<template>
  <CommonPage>
    <template #custom>
      <AppCard class="rounded-8 bg-#f6f8f9">
        <div class="mb-10 rounded-8 bg-#FFF p-24 pb-10">
          <div class="flex justify-between py-16">
            <form class="flex" @submit.prevent="methods.handleSearch">
              <n-space wrap :size="[16, 16]">
                <MyTQI>
                  <n-input
                    v-model:value="queryItems.searchVal"
                    class="w-300"
                    clearable
                    placeholder="请输入项目名称"
                  >
                    <template #suffix>
                      <n-icon size="20" :component="Search"></n-icon>
                    </template>
                  </n-input>
                </MyTQI>
                <MyTQI>
                  <AsyncSelect
                    v-model:value="queryItems.customerId"
                    class="w-200"
                    :options="methods.getCustomerOptions"
                    remote
                    :init-remote="true"
                    label-key="name"
                    value-key="id"
                  />
                </MyTQI>
                <div class="flex-shrink-0">
                  <n-button ghost type="primary" @click="methods.handleReset">
                    <i class="i-fe:rotate-ccw mr-4" />
                    重置
                  </n-button>
                  <n-button attr-type="submit" class="ml-20" type="primary">
                    <i class="i-fe:search mr-4" />
                    搜索
                  </n-button>
                </div>
              </n-space>
            </form>
            <n-button v-permission="`project_add`" type="primary" @click="$projectForm?.handleAdd">
              添加项目
            </n-button>
          </div>
          <div class="grid grid-cols-4 mt-20 gap-x-20">
            <div class="flex items-center">
              <div class="text-14 color-#030912">待启动</div>
              <div class="ml-10 rounded-10 bg-#9BA3B2 px-6 text-12 color-#FFF">{{ total1 }}</div>
            </div>
            <div class="flex items-center">
              <div>进行阶段</div>
              <div class="ml-10 rounded-10 bg-#0A56D8 px-6 text-12 color-#FFF">{{ total2 }}</div>
            </div>
            <div class="flex items-center">
              <div>运维阶段</div>
              <div class="ml-10 rounded-10 bg-#FF4D4F px-6 text-12 color-#FFF">{{ total3 }}</div>
            </div>
            <div class="flex items-center">
              <div>已完结</div>
              <div class="ml-10 rounded-10 bg-#4BD6B9 px-6 text-12 color-#FFF">{{ total4 }}</div>
            </div>
          </div>
        </div>
        <n-spin :show="data.loading">
          <n-scrollbar style="height: calc(100vh - 280px)" @scroll="methods.onScroll">
            <div class="grid grid-cols-4 gap-x-20">
              <div class="flex flex-col gap-y-12">
                <ProjectCard
                  v-for="info in list1"
                  :key="`list1-${info.id}`"
                  :info="info"
                  :levels="data.levelOptions"
                  :can-view="hasPermission('project_view')"
                  @del="methods.onDelete"
                />
              </div>
              <div class="flex flex-col gap-y-12">
                <ProjectCard
                  v-for="info in list2"
                  :key="`list2-${info.id}`"
                  :info="info"
                  :levels="data.levelOptions"
                  :can-view="hasPermission('project_view')"
                  @del="methods.onDelete"
                />
              </div>
              <div class="flex flex-col gap-y-12">
                <ProjectCard
                  v-for="info in list3"
                  :key="`list3-${info.id}`"
                  :info="info"
                  :levels="data.levelOptions"
                  :can-view="hasPermission('project_view')"
                  @del="methods.onDelete"
                />
              </div>
              <div class="flex flex-col gap-y-12">
                <ProjectCard
                  v-for="info in list4"
                  :key="`list4-${info.id}`"
                  :info="info"
                  :levels="data.levelOptions"
                  :can-view="hasPermission('project_view')"
                  @del="methods.onDelete"
                />
              </div>
            </div>
            <div
              v-if="[total1, total2, total3, total4].every((item) => item == 0) && data.isRender"
              class="flex-col items-center"
            >
              <img src="@/assets/no-data.png" class="mt-100 w-100" />
              <div class="font-size-14 color-#9BA3B2">暂无内容</div>
            </div>
          </n-scrollbar>
        </n-spin>
      </AppCard>
      <ProjectForm ref="$projectForm" @result="methods.onProject" />
    </template>
  </CommonPage>
</template>

<script setup lang="jsx">
import * as customerApi from '@/api/customer'
import { usePermissionStore } from '@/store'
import { Search } from '@vicons/ionicons5'
import { getSelArrDicts } from '@/api/dict'
import * as projectApi from '@/api/project'
import ProjectCard from './modules/ProjectCard.vue'
defineOptions({ name: 'ProjectIndex' })
const $projectForm = ref(null)
const { hasPermission } = usePermissionStore()
const useList = (projectPhase) => {
  const list = ref([])
  const page = ref(1)
  const pages = ref(1)
  const total = ref(0)
  async function getList() {
    data.loading = true
    const params = {
      page: page.value,
      limit: 10,
      projectPhase,
      ...queryItems.value,
    }
    const res = await projectApi.list(params)
    pages.value = Number(res.data.pages)
    total.value = Number(res.data.total)
    if (page.value === 1) {
      list.value = res.data.records
    } else {
      list.value = list.value.concat(res.data.records)
    }
    data.loading = false
  }
  function handleScroll() {
    if (page.value <= pages.value - 1 && !data.loading) {
      page.value++
      getList()
    }
  }
  function handleEnter() {
    page.value = 1
    return getList()
  }
  return [list, total, getList, handleScroll, handleEnter]
}
const [list1, total1, getList1, handleScroll1, handleEnter1] = useList('TO_BE_STARTED')
const [list2, total2, getList2, handleScroll2, handleEnter2] = useList('IN_PROGRESS')
const [list3, total3, getList3, handleScroll3, handleEnter3] = useList('IN_MAINTENANCE')
const [list4, total4, getList4, handleScroll4, handleEnter4] = useList('ALREADY_END')
const data = reactive({
  status: [
    { name: '待启动', code: 'TO_BE_STARTED', color: '#9BA3B2' },
    { name: '进行阶段', code: 'IN_PROGRESS', color: '#FF4D4F' },
    { name: '运维阶段', code: 'IN_MAINTENANCE', color: '#0A56D8' },
    { name: '已完结', code: 'ALREADY_END', color: '#4BD6B9' },
  ],
  levelOptions: [],
  searchVal: '',
  customerId: null,
  loading: false,
  isRender: false,
})
const queryItems = ref({
  searchVal: null,
  customerId: null,
})
const methods = reactive({
  getCustomerOptions(searchVal, id) {
    return customerApi.listAll({ searchVal, id }).then((res) => res.data)
  },
  async getLevelOptions() {
    data.levelOptions = await getSelArrDicts({ codes: 'PROJECT_LEVEL' }).then(
      (res) => res.data.PROJECT_LEVEL
    )
  },
  onDelete({ id, projectName }) {
    $projectForm.value?.handleDelete(
      { id },
      {
        title: '删除项目',
        content: `请确定是否删除项目：${projectName}`,
      }
    )
  },
  handleSearch() {
    if (hasPermission('project_list')) {
      data.isRender = false
      Promise.all([handleEnter1(), handleEnter2(), handleEnter3(), handleEnter4()]).finally(() => {
        data.isRender = true
      })
    }
  },
  handleReset() {
    queryItems.value = { searchVal: null, customerId: null }
    methods.handleSearch()
  },
  onScroll(e) {
    const dom = e.target
    const scrollDistance = dom.scrollHeight - dom.scrollTop - dom.clientHeight
    if (scrollDistance <= 1 && hasPermission('project_list')) {
      handleScroll1()
      handleScroll2()
      handleScroll3()
      handleScroll4()
    }
  },
  async getData() {
    if (hasPermission('project_list')) {
      data.isRender = false
      Promise.all([getList1(), getList2(), getList3(), getList4()]).finally(() => {
        data.isRender = true
      })
    }
  },
  onProject(type) {
    if (type === 'add') {
      $message.success(`新增项目成功!`)
      methods.getData()
    } else if (type === 'edit') {
      $message.success(`修改项目成功!`)
    } else if (type === 'del') {
      $message.success(`删除项目成功!`)
      methods.getData()
    }
  },
})

onBeforeMount(() => {
  methods.getData()
  methods.getLevelOptions()
})
</script>

<style lang="scss" scoped></style>
